<template>
  <div class="user-management">
    <el-card>
      <div slot="header" class="card-header">
        <span>用户管理</span>
        <el-button type="primary" size="small" @click="handleAdd">添加用户</el-button>
      </div>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="searchForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="禁用" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="180"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="nickname" label="昵称"></el-table-column>
        <el-table-column prop="createTime" label="注册时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row, 2)"
              v-if="scope.row.status === 1">删除</el-button>
            <el-button size="mini" type="success" @click="handleDelete(scope.row, 1)" v-else>恢复</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑用户弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="介绍" prop="introduce">
          <el-input v-model="userForm.introduce" placeholder="请输入介绍"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="userForm.status" :active-value="1" :inactive-value="2" active-text="正常"
            inactive-text="禁用">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserAdminSubmit, getUserList, getUserSubmit } from '@/api'
import { MessageBox } from 'element-ui'

export default {
  name: 'UserManagement',
  data() {
    return {
      searchForm: {
        username: '',
        email: '',
        status: ''
      },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      userList: [],
      dialogVisible: false,
      dialogType: 'add',
      dialogTitle: '添加用户',
      userForm: {
        username: '',
        email: '',
        password: '',
        status: 'active'
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        introduce: [
          { required: true, message: '请输入介绍', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchUserList()
  },
  methods: {
    async fetchUserList() {
      try {
        const params = {
          currPage: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        }
        const res = await getUserList(params)
        if (res.code === 200) {
          this.userList = res.data.list
          this.total = parseInt(res.data.total) || 0
        } else {
          this.$message.error(res.message || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$message.error('获取用户列表失败')
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchUserList()
    },
    resetSearch() {
      this.searchForm = {
        username: '',
        email: '',
        status: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchUserList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchUserList()
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTitle = '添加用户'
      this.userForm = {
        username: '',
        email: '',
        password: '',
        status: 1
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTitle = '编辑用户'
      this.userForm = {
        id: row.id,
        username: row.username,
        nickname: row.nickname,
        introduce: row.introduce,
        status: row.status
      }
      this.dialogVisible = true
    },
    handleDelete(row, status) {
      var statusText = status == 2 ? '删除' : '恢复'
      MessageBox.confirm(`确认${statusText}该用户吗？`, '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          getUserSubmit({
            id: row.id,
            status: status
          }).then(res => {
            this.$message.success(`${statusText}成功`)
            this.dialogVisible = false
            this.fetchUserList()
          }).catch(error => {
            this.$message.error(error.message || `${statusText}失败`)
          })
        } catch (error) {
          this.$message.error(`${statusText}用户失败`)
        }
      }).catch(() => { })
    },
    handleSubmit() {
      if (this.dialogTitle == '添加用户') {
        getUserAdminSubmit(this.userForm).then(res => {
          this.$message.success('提交成功')
          this.dialogVisible = false
          this.fetchUserList()
        }).catch(error => {
          this.$message.error(error.message || '提交失败')
        })
      } else {
        this.$refs.userForm.validate(async valid => {
          if (valid) {
            try {
              getUserSubmit(this.userForm).then(res => {
                this.$message.success('提交成功')
                this.dialogVisible = false
                this.fetchUserList()
              }).catch(error => {
                this.$message.error(error.message || '提交失败')
              })
            } catch (error) {
              console.error(this.dialogType === 'add' ? '添加用户失败:' : '编辑用户失败:', error)
              this.$message.error(this.dialogType === 'add' ? '添加用户失败' : '编辑用户失败')
            }
          } else {
            return false
          }
        })
      }

    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>